package at.fhv.androideightpuzzle.network.messageparsers;


import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import at.fhv.androideightpuzzle.network.message.IMessage;
import at.fhv.androideightpuzzle.network.message.StartPuzzleMessage;

public class StartPuzzleMessageParser implements IMessageParser{
	
	public StartPuzzleMessageParser(){
		//
	}
	
	public IMessage parseMessage(String message){
		try{
			JSONParser parser=new JSONParser();
			JSONObject jsonObj=(JSONObject)parser.parse(message);
			
			return parseMessage(jsonObj);
		}catch(Exception exc){
			android.util.Log.e("StartPuzzleMessageParser",exc.getMessage(),exc);
			
			return null;
		}
	}
	
	public IMessage parseMessage(JSONObject jsonObj){
		try{
			JSONObject payload=(JSONObject) jsonObj.get("payload");
			String puzzleId=(String)payload.get("puzzleid");
			
			JSONArray jsonArrParts=(JSONArray)payload.get("parts");
			int[] parts=new int[jsonArrParts.size()];
			
			for(int i=0; i<jsonArrParts.size(); i++){
				parts[i] = ((Number)jsonArrParts.get(i)).intValue();
			}
			
			JSONArray jsonArrEndstate=(JSONArray)payload.get("endstate");
			int[] endstate = new int[jsonArrEndstate.size()];
			
			for(int i=0; i<jsonArrEndstate.size(); i++){
				endstate[i]=((Number)jsonArrEndstate.get(i)).intValue();
			}
			
			int emptyPartNumber=((Number)payload.get("emptypartnumber")).intValue();
			
			return new StartPuzzleMessage(puzzleId,parts,endstate,emptyPartNumber);
		}catch(Exception exc) {
			android.util.Log.e("StartPuzzleMessageParser",exc.getMessage(),exc);
			
			return null;
		}
	}
}
